<template>
    <view class="xilu">
        <!--  -->
        <view class="page-foot bg-white">
            <view class="flex-box tc fs24 col5">
                <view class="share_btn" @tap="sharePop = true">
                    <image src="../../static/icon/detail_share.png" mode="aspectFill" class="xilu_share"></image>
                    <view class="fs24 col5">分享</view>
                </view>
                <view class="share_btn" @click="bindMessage()">
                    <image src="../../static/icon/detail_leaveword.png" mode="aspectFill" class="xilu_share"></image>
                    <view>留言</view>
                </view>
                <view class="share_btn" @click="togglesCollect()">
                    <image src="../../static/icon/detail_collect-on.png" v-if="product.is_collection_count" mode="aspectFill" class="xilu_share"></image>
                    <image src="../../static/icon/detail_collect.png" v-else mode="aspectFill" class="xilu_share"></image>
                    <view>收藏</view>
                </view>
				<template v-if="product.sale_out_status == 0">
                   <view class="btn1" @click="bindAddProduct">卖同款</view>
                    <view class="btn2" @click="bindWantProduct">我想要</view>
				</template>
                <view v-else class="btn3">商品已售出</view>
            </view>
        </view>
        <!--  -->
        <view class="container">
            <!--  -->
            <swiper class="xilu_banner" autoplay circular>
                <swiper-item v-for="(item,index) in product.images_text">
                    <image :src="item" mode="aspectFill"></image>
                </swiper-item>
            </swiper>
            <!--  -->
            <view class="p30 xilu_title fs34 fwb">{{product.name}}</view>
            <view class="plr30 pb30 pb50 flex-box flex-between">
                <view class="red fs40 fwb"><text class="fs24">¥</text>{{product.salesprice}}</view>
                <view class="fs24 col89">{{product.want_num}}人想要</view>
            </view>
            <!--  -->
            <view class="flex-box plr30 pb50">
                <image class="xilu_avatar mr20" @click="bindHome()" :src="product.user.avatar" mode="aspectFill"></image>
                <view class="flex-grow-1">
                    <view class="fs32 pb15 blue">{{product.user.nickname}}</view>
                    <view class="fs24 col89">{{product.user.logintime_text}} </view>
                </view>
                <view class="btn1 fs24" @click="toggleFocus()">{{product.is_focus_count?'已关注':'+ 关注'}}</view>
            </view>
            <!--  -->
            <view class="plr30 pb50">
                <view class="fs34 col10 fwb pb20">商品描述</view>
                <!-- 富文本 -->
                <!-- <u-parse :content="product.content"></u-parse> -->
                <text>{{product.content}}</text>
            </view>
            <!--  -->
            <view class="plr30">
                <view class="fs34 col10 fwb pb20">留言记录</view>
                <view class="xilu_leave_word flex-box pb30 mt30 flex-align-start" v-for="(item,index) in messageList">
                    <image class="xilu_avatar mr30" :src="item.user.avatar" mode="aspectFill"></image>
                    <view class="flex-grow-1">
                        <view class="flex-box flex-between pb10">
                            <view class="fs30 col5">{{item.user.nickname}}</view>
                            <view class="fs24 col89">{{item.createtime_text}}</view>
                        </view>
                        <view class="fs30 col10">{{item.content}}</view>
                    </view>
                </view>
            </view>
        </view>
        <canvas style="width: 650px;height: 1064px;position: fixed;top: -999em;right: -999em;" canvas-id="myCanvas" id="myCanvas1"></canvas>
        <u-popup :show="sharePop" mode="bottom" round="20" closeOnClickOverlay closeable @cancel="sharePop = false" @close="sharePop = false">
            <view class="bottom_pop">
                <view class="pb50 tc fs34 col3">分享</view>
                <view class="flex-box flex-around">
                    <button hover-class="none" open-type="share">
                        <image src="/static/icon/share1.png" mode="aspectFill" class="icon_share"></image>
                        <view>微信</view>
                    </button>
                    <button hover-class="none">
                        <image src="/static/icon/share2.png" mode="aspectFill" class="icon_share"></image>
                        <view>朋友圈</view>
                    </button>
                    <button hover-class="none" @tap.stop="showCanvas">
                        <image src="/static/icon/share3.png" mode="aspectFill" class="icon_share"></image>
                        <view>海报</view>
                    </button>
                </view>
            </view>
        </u-popup>
        <u-popup :show="canvasPop" mode="center" round="20" closeOnClickOverlay @cancel="canvasPop = false" @close="canvasPop = false" customStyle="background:transparent;">
            <image :src="imgPath" style="width: 650rpx;height: 1064rpx;display: block;border-radius: 30rpx;"></image>
            <!-- <image src="/static/icon/close.png" class="close" mode="aspectFill" @tap.stop="canvasPop = false"></image> -->
            <view class="flex-box flex-center">
                <view class="btns btn1" @tap.stop="canvasPop = false">取消</view>
                <view class="btns btn2" @tap.stop="saveImage">保存图片</view>
            </view>
        </u-popup>
        <u-popup :show="msgPop" mode="bottom" round="20" closeOnClickOverlay closeable @cancel="bindMessage()" @close="bindMessage()">
            <view class="ptb50 tc fs34 col3">留言记录</view>
            <view class="msg_pop flex-box flex-col">
                <view class="flex-grow-1" style="width: 100%;">
                    <mescroll-uni @init="mescrollInit" @down="downCallback" @up="upCallback" :fixed="false">
                        <view class="xilu_leave_word" v-for="(item,index) in productMessage" :key="index">
                            <view class="flex-box flex-align-start ptb30">
                                <image class="xilu_avatar mr30" :src="item.user.avatar" mode="aspectFill"></image>
                                <view class="flex-grow-1">
                                    <view class="flex-box flex-between pb10">
                                        <view class="fs30 blue">{{item.user.nickname}}</view>
                                        <view class="fs24 col89">{{item.createtime_text}}</view>
                                    </view>
                                    <view class="fs30 col10" @click="bindApply(index,-1)">{{item.content}}</view>
                                </view>
                            </view>
                            <view class="xilu_reply flex-box ptb30 mb30 flex-align-start" v-if="!item.childCommentsMore.nothing" v-for="(item2,index2) in item.childComments">
                                <image class="xilu_avatar mr15" :src="item2.user.avatar" mode="aspectFill"></image>
                                <view class="flex-grow-1">
                                    <view class="flex-box flex-between pb10">
                                        <view class="fs30 blue">{{item2.user.nickname}}</view>
                                        <view class="fs24 col89">{{item2.createtime_text}}</view>
                                    </view>
                                    <view class="fs30 col10" @click="bindApply(index,index2)">{{item2.content}}</view>
                                </view>
                            </view>
                            <view class="flex-box flex-center ptb30" v-if="item.childlist_count>0">
                                <view class="m-arrow-down" @click="fetchSecondComments(index)" v-if="item.childCommentsMore.page==1"><text class="pr10">展开{{item.childlist_count}}评论</text></view>
                                <view class="m-arrow-down" @click="fetchSecondComments(index)" v-else-if="item.childCommentsMore.page>1 && !item.childCommentsMore.nomore"><text class="pr10">加载更多</text></view>
                                <view class="m-arrow-up ml30" v-if="item.childCommentsMore.page>1" @click="bindRetract(index)"><text class="pr10">收起</text></view>
                            </view>
                        </view>
                    </mescroll-uni>
                </view>
                <view class="flex-box pb50">
                    <input type="text" class="input plr30 mr30" placeholder-class="colc" :placeholder="replayText?replayText:'说点什么～'" :focus="focusStatus" v-model="content" />
                    <view class="send" @click="addComment">发送</view>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
    import canvas from '@/xilu/canvas.js'
    // 引入mescroll-mixins.js
    import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
    export default {
        mixins: [MescrollMixin], // 使用mixin
        data() {
            return {
                productId: 0,
                product: {
                    name: '',
                    category_id: '',
                    content: '',
                    images: '',
                    salesprice: '0.00',
                    freight_status: '',
                    freight_money: '0.00',
                    createtime_text: '',
                    want_num: 0,
                    user: {
                        id: '',
                        nickname: '',
                        avatar: '',
						logintime_text:''
                    }
                },
                messageList: [],
                messageListMore: {
                    page: 1
                },
                sharePop: false, //分享弹窗
                canvasPop: false, //海报弹窗

                goodsImg: {}, // 商品图信息1
                ewmImg: {}, // 二维码图片信息
                avatarImg: {}, // 头像信息
                isShow: false, //显示保存按钮
                imgPath: "", //生成的图片路径

                msgPop: false, //留言弹窗
                productMessage: [],
                firstIndex: -1,
                secondIndex: -1,
                focusStatus: false,
                replayText: '',
                content: ''
            }
        },
        onLoad(options) {
            this.productId = options.id || 0;
            this.fetchDetail();
            // this.fetchMessage();
        },
        onShareAppMessage(e) {
            const promise = new Promise(resolve => {
                setTimeout(() => {
                    resolve({
                        title: this.product.name
                    })
                }, 200)
            })
            return {
                title: this.product.name,
                path: '/pages/goods_detail/goods_detail?id=' + this.product.id,
                imageUrl: this.product.images_text.length > 0 ? this.product.images_text[0] : '',
                promise
            }
        },
        onShareTimeline() {
            const promise = new Promise(resolve => {
                setTimeout(() => {
                    resolve({
                        title: this.product.name
                    })
                }, 200)
            })
            return {
                title: this.product.name,
                path: '/pages/goods_detail/goods_detail?id=' + this.product.id,
                imageUrl: this.product.images_text.length > 0 ? this.product.images_text[0] : '',
                promise
            }
        },
        methods: {
            //详情
            fetchDetail() {
                this.$core.get({
                    url: 'xilumarket.product/detail',
                    data: {
                        product_id: this.productId
                    },
                    success: ret => {
                        this.product = ret.data
                    },
                    fail: err => {
                        console.log(err);
						uni.showModal({
							title: '提示',
							content: err.msg,
							showCancel:false,
							success() {
								uni.navigateBack();
							}
						})
						return false;
                    }
                });
            },
            bindMessage() {
                this.msgPop = !this.msgPop;
                this.resetMessage()
            },
            //留言数据重置
            resetMessage() {
                this.replayText = '';
                this.firstIndex = -1;
                this.secondIndex = -1;
                this.content = '';
                this.replayText = '';
                this.focusStatus = false;
            },

            //海报
            showCanvas() {
                if (!this.$core.getUserinfo(true)) {
                    return '';
                }
                let platform = 'h5';
                // #ifdef MP-WEIXIN
                platform = 'wxmini';
                // #endif
                this.$core.get({
                    url: 'xilumarket.product/poster_info',
                    data: {
                        platform: platform,
                        product_id: this.productId
                    },
                    success: ret => {
                        this.loadCavas(ret.data);
                    },
                    fail: err => {
                        console.log(err);
                    }
                })
            },
            async loadCavas(poster) {
                let that = this;
                // 获取背景图，二维码信息等，APP端会返回图片的本地路径（H5端只能返回原路径）
                let avatarImgUrl = poster.img1;
                let goodsImgUrl = poster.img3; // 主图本地路径，也可以用网络地址
                let ewmImgUrl = poster.img2;
                that.avatarImg = await that.getImageInfo(avatarImgUrl);
                that.goodsImg = await that.getImageInfo(goodsImgUrl);
                that.ewmImg = await that.getImageInfo(ewmImgUrl);

                // 如果主图，二维码图片，设备信息都获取成功，开始绘制海报，这里需要用setTimeout延时绘制，否则可能会出现图片不显示。
                if (that.goodsImg.errMsg == 'getImageInfo:ok' && that.ewmImg.errMsg == 'getImageInfo:ok' && that.avatarImg.errMsg == 'getImageInfo:ok') {
                    console.log('读取图片信息成功')
                    uni.showToast({
                        icon: 'loading',
                        mask: true,
                        duration: 10000,
                        title: '海报绘制中',
                    });
                    setTimeout(() => {
                        // 获取canvas上下文
                        var ctx = uni.createCanvasContext('myCanvas', that);
                        // 1.填充背景色，白色
                        ctx.setFillStyle('#fff'); // 默认白色
                        ctx.fillRect(0, 0, 650, 1064) // fillRect(x,y,宽度，高度)

                        // 2. 绘制头像，昵称
                        canvas.clipCircleImg(ctx, 30, 30, 25, that.avatarImg.path);
                        canvas.fillTextCut(ctx, poster.nickname, 32, 32, 100, 39, 550, 1, false, "#333");

                        // 3.绘制商品图
                        ctx.drawImage(that.goodsImg.path, 30, 110, 590, 590); // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度)

                        // 4.绘制白色矩形
                        canvas.clipRoundRect(ctx, 0, 912, 650, 152, 0, '#FFC100');

                        // 5.绘制昵称，提示语
                        canvas.fillTextCut(ctx, poster.text2, 34, 34, 30, 947, 308, 1, false, "#101010");
                        canvas.fillTextCut(ctx, poster.text3, 28, 28, 30, 1001, 308, 1, false, "#616161");

                        // 6.绘制二维码
                        ctx.drawImage(that.ewmImg.path, 520, 938, 100, 100); // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度)

                        // 7.绘制简介
                        canvas.fillTextCut(ctx, poster.text1, 34, 44, 30, 730, 590, 2, false, "#101010");

                        // 7.绘制现价
                        canvas.fillTextCut(ctx, '¥' + poster.salesprice, 34, 34, 30, 847, 140, 1, false, "#FE3846");

                        // 8.绘制原价
                        canvas.fillTextCut(ctx, '原价¥' + poster.line_price, 24, 24, 170, 850.5, 140, 1, false, "#898989");
                        canvas.clipRoundRect(ctx, 170, 859, 120, 1, 0, '#898989');

                        // 8.绘制想要
                        canvas.fillTextCut(ctx, poster.want_num + '人想要', 24, 24, 509, 853, 111, 1, false, "#898989");

                        // draw方法 把以上内容画到 canvas 中
                        ctx.draw(true, (ret) => {
                            that.isShow = true // 显示按钮-保存图片到相册

                            uni.showToast({
                                icon: 'success',
                                mask: true,
                                title: '绘制完成',
                            });
                            uni.canvasToTempFilePath({ // 保存canvas为图片
                                canvasId: 'myCanvas',
                                quality: 1,
                                complete: function(res) {
                                    // 在H5平台下，tempFilePath 为 base64, // 图片提示跨域 H5保存base64失败，APP端正常输出临时路径
                                    that.imgPath = res.tempFilePath;
                                    uni.setStorageSync('filePath', res.tempFilePath); //保存临时文件路径到缓存
                                    that.canvasPop = true;
                                    that.sharePop = false;
                                },
                            })
                        });
                    }, 1500)

                } else {
                    console.log('读取图片信息失败');
                }
            },
            // 获取图片信息
            getImageInfo(image) {
                return new Promise((req, rej) => {
                    uni.getImageInfo({
                        src: image,
                        success: function(res) {
                            req(res)
                        },
                    });
                })
            },
            // 保存图片到相册
            saveImage() {
                let imgPath = this.imgPath
                uni.saveImageToPhotosAlbum({
                    filePath: imgPath,
                    success(res) {
                        uni.showToast({
                            icon: 'success',
                            mask: true,
                            title: '保存成功',
                        });
                    },
                    fail(res) {
                        console.log(res.errMsg)
                    }
                })
            },

            //重新加载
            reloadList() {
                this.mescroll.resetUpScroll();
            },
            /*上拉加载的回调*/
            upCallback(page) {
                // 此处可以继续请求其他接口
                let pageNum = page.num; // 页码, 默认从1开始
                let pageSize = page.size; // 页长, 默认每页10条
                this.$core.get({
                    url: 'xilumarket.product_message/lists',
                    data: {
                        product_id: this.productId,
                        page: pageNum,
                        pageSize: pageSize
                    },
                    success: (ret) => {
                        let data = ret.data;
                        // 接口返回的当前页数据列表 (数组)
                        let curPageData = data.data;
                        // 接口返回的当前页数据长度 (如列表有26个数据,当前页返回8个,则curPageLen=8)
                        let curPageLen = curPageData.length;
                        // 接口返回的总页数 (如列表有26个数据,每页10条,共3页; 则totalPage=3)
                        let totalPage = data.last_page;
                        // 接口返回的总数据量(如列表有26个数据,每页10条,共3页; 则totalSize=26)

                        //设置列表数据
                        if (page.num == 1) this.productMessage = []; //如果是第一页需手动置空列表
                        this.productMessage = this.productMessage.concat(curPageData); //追加新数据
						if(page.num == 1) this.messageList = curPageData;
                        // 请求成功,隐藏加载状态
                        //方法一(推荐): 后台接口有返回列表的总页数 totalPage
                        this.mescroll.endByPage(curPageLen, totalPage);

                        setTimeout(() => {
                            this.mescroll.endSuccess(curPageLen)
                        }, 20)
                    },
                    fail: () => {
                        //  请求失败,隐藏加载状态
                        this.mescroll.endErr()
                    }
                })

            },
            //二级评论
            fetchSecondComments(firstIndex) {
                this.$util.fetch2(this, 'xilumarket.product_message/second_lists', {
                    product_id: this.productId,
                    product_message_id: this.productMessage[firstIndex].id,
                    pagesize: 10
                }, "childCommentsMore", "childComments", 'productMessage', firstIndex, 'data', data => {

                })
            },
            //收起
            bindRetract(firstIndex) {
                this.productMessage[firstIndex].childComments = [];
                this.productMessage[firstIndex].childCommentsMore = {
                    page: 1
                };
            },
            //发布留言
            addComment() {
                let firstIndex = this.firstIndex;
                let secondIndex = this.secondIndex;
                let pid = 0;
                if (firstIndex >= 0 && secondIndex >= 0) {
                    pid = this.productMessage[firstIndex].childComments[secondIndex].id;
                } else if (firstIndex >= 0) {
                    pid = this.productMessage[firstIndex].id;
                }
                if (!this.content.trim()) {
                    uni.showToast({
                        title: "还是说点啥吧～",
                        icon: 'none'
                    })
                    return ''
                }
                this.$core.post({
                    url: 'xilumarket.product_message/add_message',
                    data: {
                        product_id: this.product.id,
                        pid: pid,
                        content: this.content
                    },
                    success: ret => {
                        uni.showToast({
                            title: "点评成功",
                            icon: 'none'
                        });
                        this.reloadList();
                        this.resetMessage();
                    },
                    fail: err => {
                        console.log(err);
                    }
                });
            },
            //回复留言
            bindApply(index, index2) {
                this.firstIndex = index;
                this.secondIndex = index2;
                this.replayText = "回复 @" + (index2 > -1 ? this.productMessage[index].childComments[index2].user.nickname : this.productMessage[index].user.nickname)
                this.focusStatus = true;
            },
            // 关注取关
            toggleFocus() {
                if (!this.$core.getUserinfo(true)) {
                    return true;
                }
                this.$core.post({
                    url: 'xilumarket.forum/toggle_focus',
                    data: {
                        user_id: this.product.user_id
                    },
                    success: ret => {
                        this.product.is_focus_count = ret.data.is_focus_count;
                        this.$forceUpdate();
                    },
                    fail: err => {
                        console.log(err);
                    }
                });
            },
            // 点击收藏
            togglesCollect() {
                this.$core.post({
                    url: 'xilumarket.product/toggle_collection',
                    data: {
                        product_id: this.product.id
                    },
                    success: ret => {
                        this.product.is_collection_count = ret.data.is_collection_count;
                        this.$forceUpdate();
                    },
                    fail: err => {}
                });
            },

            bindAddProduct() {
                if (!this.$core.getUserinfo(true)) {
                    return ''
                }
                let product = {
                    name: this.product.name,
                    category_id: this.product.category_id,
                    province_id: this.product.province_id,
                    city_id: this.product.city_id,
                    region_id: this.product.region_id,
                    address: this.product.address,
                    content: this.product.content,
                    images: this.product.images_text,
                    salesprice: this.product.salesprice,
                    line_price: this.product.line_price,
                    freight_status: this.product.freight_status,
                    freight_money: this.product.freight_money
                }
                this.$core.checkAuth(function() {
                    uni.navigateTo({
                        url: '/pages/public_xianzhi/public_xianzhi',
                        success(res) {
                            res.eventChannel.emit('addProductTransfor', product)
                        }
                    })
                })
            },
            //我想要
            bindWantProduct() {
                if (!this.$core.getUserinfo(true)) {
                    return ''
                }
                if (!getApp().globalData.chat_config.SocketTask) {
                    uni.showToast({
                        title: '即时通过未开启',
                        icon: 'none'
                    })
                    return false;
                }
                let product = {
                    id: this.product.id,
					product_type: this.product.product_type,
                    name: this.product.name,
                    want_num: this.product.want_num,
                    thumb_image_text: this.product.thumb_image_text,
                    salesprice: this.product.salesprice,
                    freight_status: this.product.freight_status,
                    freight_money: this.product.freight_money,
                    to_username: this.product.user ? this.product.user.nickname : ''
                }
                uni.navigateTo({
                    url: '/pages/chat/chat?receive_user_id=' + this.product.user_id + '&product_id=' + this.product.id,
                    success(res) {
                        res.eventChannel.emit('chatProductTransfor', product)
                    }
                })
            },
			bindHome() {
			    uni.navigateTo({
			        url: '/pages/home_page/home_page?id=' + this.product.user_id + '&tab=product'
			    })
			}
        }
    }
</script>

<style lang="scss" scoped>
    .xilu {
        &_banner {
            width: 750rpx;
            height: 750rpx;

            image {
                width: 750rpx;
                height: 750rpx;
            }
        }

        &_title {
            color: #101010;
            line-height: 48rpx;
        }

        &_avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
        }

        .btn1 {
            height: 54rpx;
            line-height: 54rpx;
            width: 110rpx;
        }

        &_share {
            width: 45rpx;
            height: 45rpx;
        }

        .share_btn {
            line-height: 1;
            padding: 0;
            margin: 0;
            border: none;
            padding-right: 30rpx;
            padding-left: 10rpx;

            image {
                margin-bottom: 8rpx;
            }

            &::after {
                border: none;
            }
        }

        .page-foot {
            .flex-box {
                padding: 10rpx 30rpx;

                .share_btn:first-child {
                    padding-left: 0;
                }
            }

            .btn1,
            .btn2{
                width: 160rpx;
                height: 80rpx;
                line-height: 78rpx;
                font-size: 30rpx;
                color: #101010;
            }

            .btn1 {
                margin-left: auto;
                margin-right: 20rpx;
            }
            .btn3{
                flex:1;
                height: 80rpx;
                line-height: 78rpx;
                font-size: 30rpx;
                color: #101010;
            }
        }

        .icon_share {
            width: 90rpx;
            height: 90rpx;
            margin-bottom: 20rpx;
            border-radius: 50%;
        }

        .close {
            width: 48rpx;
            height: 48rpx;
            display: block;
            margin: 40rpx auto 0;
        }

        &_leave_word {
            border-bottom: 1px solid #eee;
        }

        &_reply {
            padding: 30rpx;
            background: #F7F9FC;
            border-radius: 15rpx;
        }

        .msg_pop {
            width: 100%;
            padding: 0 30rpx;
            height: 80vh;
        }

        .btns {
            width: 250rpx;
            height: 90rpx;
            line-height: 90rpx;
            border: none;
            margin: 60rpx 20rpx 0;
        }

        .btns.btn1 {
            background: #E5E5E5;
        }

        .btns.btn2 {
            background: #FFC100;
        }

        .input {
            width: 540rpx;
            height: 80rpx;
            background: #F7F9FC;
            border-radius: 43rpx;
            font-size: 26rpx;
        }

        .send {
            width: 120rpx;
            height: 80rpx;
            line-height: 80rpx;
            background: #FFC100;
            border-radius: 43rpx;
            font-size: 30rpx;
            color: #101010;
            text-align: center;
        }
    }
</style>